package org.alvin.i18n.ui;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CWordTrimUtil {

    public static void main(String[] args) throws IOException {
//        String dir = "D:/i18n/需要翻译的内容/需要翻译的内容/小蓝后台/中文内容";
        String dir = "D:\\i18n\\需要翻译的内容\\需要翻译的内容\\小蓝小程序\\需要翻译的中文";
        Files.list(Paths.get(dir)).filter(item -> item.getFileName().toString().endsWith(".txt")).forEach(path -> {
            try {
                fileMap(path);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    private static void fileMap(Path path) throws IOException {
        byte[] buff = Files.readAllBytes(path);
        String text = new String(buff, StandardCharsets.UTF_8);
        int index = text.indexOf("{");
        JSONObject jsonObject = JSONObject.parseObject(text.substring(index));
        JSONObject wordMapJson = new JSONObject();


        for (String key : jsonObject.keySet()) {
            JSONObject childJson = jsonObject.getJSONObject(key);
            for (String ckey : childJson.keySet()) {
                String fullKey = key.concat(".").concat(ckey);
                String value = childJson.getString(ckey);
                if (!wordMapJson.containsKey(value)) {
                    wordMapJson.put(value, new JSONArray());
                }
                JSONArray jsonArray = wordMapJson.getJSONArray(value);
                jsonArray.add(fullKey);
                wordMapJson.put(value, jsonArray);
            }
        }
        Path mapPath = Paths.get(path.getParent().toFile().getAbsolutePath(), path.getFileName().toString() + ".map");

        String outString = JSON.toJSONString(wordMapJson, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat);
        Files.write(mapPath, outString.getBytes(StandardCharsets.UTF_8));

        //
        JSONObject trimJson = new JSONObject();
        for (String key : wordMapJson.keySet()) {
            JSONArray jsonArray = wordMapJson.getJSONArray(key);
            String realKey = jsonArray.getString(0);
            String realValue = key;
            trimJson.put(realKey, realValue);
        }
        Path realPath = Paths.get(path.getParent().toFile().getAbsolutePath(), path.getFileName().toString() + ".real");

        outString = JSON.toJSONString(trimJson, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat);
        Files.write(realPath, outString.getBytes(StandardCharsets.UTF_8));
    }
}
